package com.wct.permission.service;

import com.wct.permission.domain.SysRole;
import com.wct.permission.domain.SysUser;
import com.wct.permission.mapper.UserDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author WEI (Email:changtan20000@163.com)
 * @description
 * @date 2020/2/13 20:17
 */
@Slf4j
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)) {
            return null;
        }

        try {
            SysUser sysUser = userDao.findByUsername(username);
            if (sysUser == null) {
                return null;
            }

            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));


            List<SysRole> roles = sysUser.getRoles();
            if (roles != null || roles.size() > 0) {
                roles.forEach(sysRole -> authorities.add(new SimpleGrantedAuthority(sysRole.getRoleName())));
            }

            authorities.forEach(authority -> log.info("{} have {}", username, authority));

//            return new User(sysUser.getUsername(), sysUser.getPassword(), authorities);
            return new User(sysUser.getUsername(), sysUser.getPassword(),
                    sysUser.getStatus() == 1,
                    true,
                    true,
                    true,
                    authorities);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
